import pandas as pd
import re
import time

from Core.Config import Config
config = Config()
database = config.DataBase()
#database.creatIndex("Recommender", "UserAction", "Key")
#database.creatIndex("Recommender", "UserAction", "userpin")
#database.creatIndex("Recommender", "UserAction", "articleId")
#database.creatIndex("Recommender", "UserAction", "user_systime")
#database.creatIndex("Recommender", "UserAction_Plus", "user_systime")

def user_action_gpapp(para):
    data = pd.read_csv(r'C:\Users\zhujunheng\Desktop\user_flow_gpapp.csv', header=1, sep=',',
                       names=["deviceid", 'userpin', 'sys_time', 'h5_url', 'visit_times', 'visit_stay_time',
                              'session_seq'], dtype={'date': str}, encoding='GBK')

    for i in range(len(data)):
        deviceid = data.loc[i, "deviceid"]
        userpin = data.loc[i, "userpin"]
        visit_stay_time = int(data.loc[i, "visit_stay_time"])
        visit_times = int(data.loc[i, "visit_times"])
        sys_time = data.loc[i, "sys_time"]
        session_seq = data.loc[i, "session_seq"]
        source = "gpapp"
        a = data.loc[i, "h5_url"]

        b = re.search("articleId=", a)
        if b == None:
            continue

        d = b.regs[0][1]
        debig = 1
        j = d
        e = ""
        while j < len(a) and a[j].isdigit() == True:
            e += a[j]
            j += 1
        # print(e)
        articleId = e

        # print(userflow[deviceid])
        followersDoc = {}
        followersDoc["user_systime"] = sys_time
        Time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        followersDoc["Updatetime"] = Time
        followersDoc["deviceid"] = deviceid
        followersDoc["userpin"] = userpin
        followersDoc["user_systime"] = sys_time
        followersDoc["visit_times"] = visit_times
        followersDoc["visit_stay_time"] = visit_stay_time
        followersDoc["session_seq"] = int(session_seq)
        followersDoc["articleId"] = articleId
        followersDoc["source"] = source
        followersDoc['like_item'] = likeornot(articleId, visit_stay_time, para)

        followersDoc["Key"] = deviceid + "_" + articleId + "_" + sys_time
        print(articleId,followersDoc['like_item'] )
        #database.upsert("Recommender", "UserAction", {"Key": followersDoc["Key"]}, followersDoc)

def user_profile():
    data = pd.read_csv(r'C:\Users\zhujunheng\Desktop\userprofile.csv', header=0, sep=',', dtype={'date': str}, encoding='GBK')

    for i in range(len(data)):

        userpin = data.loc[i, "real_pin"]
        level = data.loc[i, "cpp_base_ulevel"]
        if level == -1:
            level = None
        sex = data.loc[i, "cpp_base_sex"]
        if sex == -1:
            sex = None
        age = data.loc[i, "cpp_base_age"]
        if age == -1:
            age = None
        marriage = data.loc[i, "cpp_base_marriage"]
        if marriage == -1:
            marriage = None
        education = int(data.loc[i, "cpp_base_education"])
        if education == -1:
            education = None
        elif education == 1:
            education = "初中及以下"
        elif education == 2:
            education = "高中"
        elif education == 3:
            education = "大学"
        elif education == 4:
            education = "硕士及以上"
        profession = data.loc[i, "cpp_base_profession"]
        if profession == -1:
            profession = None
        elif profession == "a":
            profession = "金融从业者"
        elif profession == "b":
            profession = "医务人员"
        elif profession == "c":
            profession = "公务员/事业单位"
        elif profession == "d":
            profession = "白领/一般职员"
        elif profession == "e":
            profession = "工人/服务业人员"
        elif profession == "f":
            profession = "教师"
        elif profession == "g":
            profession = "农民"
        elif profession == "h":
            profession = "学生"
        province = data.loc[i, "cpp_addr_province"]
        if province == -1:
            province = None
        purchase_power = int(data.loc[i, "cgp_cust_purchpower"])
        if purchase_power == -1:
            purchase_power == None
        elif purchase_power == 1:
            purchase_power == "土豪"
        elif purchase_power == 2:
            purchase_power = "高级白领"
        elif purchase_power == 3:
            purchase_power = "白领"
        elif purchase_power == 4:
            purchase_power = "蓝领"
        elif purchase_power == 5:
            purchase_power = "收入很少"

        # print(userflow[deviceid])
        followersDoc = {}
        Time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        followersDoc["Updatetime"] = Time
        followersDoc["userpin"] = userpin
        followersDoc["level"] = level
        followersDoc["sex"] = sex
        followersDoc["age"] = age
        followersDoc["marriage"] = marriage
        followersDoc["education"] = education
        followersDoc["profession"] = profession
        followersDoc["province"] = province
        followersDoc["purchase_power"] = purchase_power
        followersDoc["source"] = "gpapp"

        followersDoc["Key"] = userpin
        print(followersDoc)
        #database.upsert("Recommender", "UserProfile", {"Key": followersDoc["Key"]}, followersDoc)

def likeornot(articleId, visit_stay_time,para):
        article_detail = database.find("Recommender", 'Article', query={'Key': articleId})
        if len(article_detail) == 0:
            return 0
        else:
            if article_detail[0]["length"] == 0:
                std_visit_time = visit_stay_time
            else:
                std_visit_time = visit_stay_time / article_detail[0]["length"]
            if std_visit_time < para:
                return -1
            else:
                return 1


def user_action_myDB():
    data = pd.read_csv(r'C:\Users\zhujunheng\Desktop\user_action_myDB.csv', header=0, sep=',', dtype={'date': str}, encoding='GBK')

    for i in range(len(data)):

        userpin = data.loc[i, "create_user"]
        type = data.loc[i, "type"]
        status = data.loc[i, "status"]
        article_id = str(data.loc[i, "article_id"])
        create_time = data.loc[i, "create_time"]
        if status == 2:
            continue


        # print(userflow[deviceid])
        followersDoc = {}

        followersDoc["userpin"] = userpin
        followersDoc["type"] = type
        followersDoc["article_id"] = article_id
        followersDoc["action_time"] = create_time
        followersDoc["source"] = "gpapp"

        followersDoc["Key"] = userpin + "_" + article_id + "_" + create_time
        print(followersDoc)
        #database.upsert("Recommender", "UserAction_Plus", {"Key": followersDoc["Key"]}, followersDoc)


#user_action_gpapp(35)
#user_profile()
user_action_myDB()